import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FinanceService} from '../finance.service';
import {MainService} from '../../../public/service/main.service';
import {Enums} from '../../../public/setting/enums';
import {UserService} from '../../user/user.service';

@Component({
  selector: 'app-recharge',
  templateUrl: './recharge.component.html',
  styleUrls: ['./recharge.component.css']
})
export class RechargeComponent implements OnInit {
  public validateForm: FormGroup;//充值的表单
  public isConfirmLoading: boolean = false;//充值中
  public isDeductLoading: boolean = false;//扣除中
  public isOkLoading: boolean = false;//查询中
  public rechargeType = this.mainService.getEnumDataList(Enums.RechargeType);
  public realName: string;

  constructor(private fb: FormBuilder, public financeService: FinanceService,
              public mainService: MainService, public userService: UserService) {
    this.validateForm = this.fb.group({
      account: [null, Validators.compose([Validators.required, Validators.maxLength(32)])],
      type: [null, Validators.compose([Validators.required])],
      num: [null, Validators.compose([Validators.required])],
    });
  }

  ngOnInit() {
  }

  /**
   * 充值
   */
  recharge() {
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isConfirmLoading = true;
    let formData = Object.assign({}, this.validateForm.value);
    //addLeader
    this.financeService.addBalance(formData).then((data: any) => {
      this.isConfirmLoading = false;
      this.reset();
    }).catch(res => this.isConfirmLoading = false);
  }

  /**
   * 扣除
   */
  deduct() {
    //1.进行脏检查，提示未填的必填字段
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
    }
    if (this.validateForm.invalid) return;
    this.isDeductLoading = true;
    let formData = Object.assign({}, this.validateForm.value);
    //addLeader
    this.financeService.deductBalance(formData).then((data: any) => {
      this.isDeductLoading = false;
      this.reset();
    }).catch(res => this.isDeductLoading = false);
  }

  /**
   * 获取账户
   */
  getAccount() {
    let account = this.validateForm.value.account;
    if(account) this.isOkLoading = true;
    this.userService.getAccount(account).then((data: any) => {
      if (data) {
        this.realName = data.realName;
        let me = this;
        setTimeout(function () {
          me.isOkLoading = false;
        },200)
      }
    });
  }

  reset() {
    this.validateForm.reset();
  }

  getFormControl(name) {
    return this.validateForm.controls[name];
  }

}
